﻿using Front_Efcore.Entity.subarea;
using Frontdatabase.Entity;
using Frontdatabase.Entity.Base;
using Frontdatabase.Entity.Video;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Frontdatabase
{
    /// <summary>
    /// 前台项目数据库上下文
    /// <para>操作数据库的对象</para>
    /// </summary>
    public class FrontDbContext : DbContext
    {
        public FrontDbContext(DbContextOptions options) : base(options)   {    }

        public DbSet<User> Users { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Subarea> SubAreas { get; set; }
        public DbSet<VideoEntity> VideoEntities { get; set; }
        public DbSet<VideoList> VideoList { get; set; }
        public DbSet<VideoCompilations> VideoCompilations { get; set; }
        /// <summary>
        /// 保存时更新时间
        /// </summary>
        /// <returns></returns>
        public override int SaveChanges()
        {
            //自动修改 CreateTime,UpdateTime
            var entityEntries = ChangeTracker.Entries().ToList();
            foreach (var entity in entityEntries)
            {
               var now= DateTime.Now;
                if (entity.State == EntityState.Added)
                {
                    Entry(entity.Entity).Property(nameof(EntityBase.Create_Time)).CurrentValue = now;
                    Entry(entity.Entity).Property(nameof(EntityBase.UpDate_Time)).CurrentValue = now;

                }
                else if (entity.State == EntityState.Modified)
                { Entry(entity.Entity).Property(nameof(EntityBase.UpDate_Time)).CurrentValue =now; }

            }
            return base.SaveChanges();
        }
    }

}
